package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock  implements  ILock{
//    这个name是区分不同业务的锁（我一人一单的业务要加分布式锁，别的业务也可可能加）
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * key 的前缀
     */
    private static final  String KEY_PREFIX = "lock:";
    /**
     * 线程标识前缀 等会拼上线程id 构成线程标识
     */
    private static final  String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);

    }


    /**
     * 获取锁
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
//      线程标识
        String id =ID_PREFIX+Thread.currentThread().getId();
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, id, timeoutSec, TimeUnit.SECONDS);
//      Boolean <-    boolean 避免拆箱 null的问题
        return Boolean.TRUE.equals(flag);
    }
    /**
     * 释放锁
     */
    @Override
    public void unlock() {
        /**
         * 调用lua脚本
         */
    stringRedisTemplate.execute(
            UNLOCK_SCRIPT,
            Collections.singletonList(KEY_PREFIX + name),
            ID_PREFIX+Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {
//        String id =ID_PREFIX+Thread.currentThread().getId();
//        String value = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
////        判断标识是否一致
//        if(id.equals(value)) {
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//
//    }
}
